package com.eptok.gw.szcups.hsm;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eptok.gw.szcups.common.PropertyLoader;

/**
 * 加密机通讯类
 * 
 *@author:heqishan, Email:heqishan@gmail.com
 *2013-3-7 下午02:10:23
 */
public class HsmSocket {
	
	private static final int HSM_SOCKET_CONNECT_TIMEOUT = 5000;
	private static final int HSM_SOCKET_READ_TIMEOUT = 10000;
	
	private static final Logger log = LoggerFactory.getLogger(HsmSocket.class);
	
	public HsmSocket(){
		
	}
	
	public String getHsmData(String request) throws IOException{
		Socket socket = null;
		DataOutputStream doc = null;
		DataInputStream in = null;
		String response = null;
		try {
			log.debug("连接加密机"+PropertyLoader.getInstance().getHsmIp()+":"+PropertyLoader.getInstance().getHsmPort());
			InetAddress addr = InetAddress.getByName(PropertyLoader.getInstance().getHsmIp());
			socket = new Socket();
			
			//设置连接超时时间
			socket.connect( new InetSocketAddress(addr,PropertyLoader.getInstance().getHsmPort()), HSM_SOCKET_CONNECT_TIMEOUT );
			//设置读内容超时时间
			socket.setSoTimeout(HSM_SOCKET_READ_TIMEOUT);
			
            doc = new DataOutputStream(socket.getOutputStream());   
            in = new DataInputStream(socket.getInputStream());
            
            doc.writeUTF(request);
            doc.flush();
            log.info("发送给加密机的数据:" + request);
            
            response = in.readUTF();
            log.info("获取加密机返回数据:" + response);
            
		}catch (IOException e) {
			log.error("加密机通讯出错",e);
			throw e;
		} finally{
			if(socket!=null){ 
				try {
					in.close();
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return response;
	}

}
